<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('我的画廊')" />
    <style>
        .gallery-item {
            margin-bottom: 20px;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        .gallery-header {
            padding: 10px 15px;
            border-bottom: 1px solid #eee;
        }
        .gallery-title {
            font-size: 16px;
            font-weight: bold;
            margin: 0;
        }
        .gallery-date {
            font-size: 12px;
            color: #888;
            margin-top: 5px;
        }
        /* 添加编辑按钮样式 */
        .edit-btn {
            position: absolute;
            top: 10px;
            right: 15px;
            font-size: 16px;
            color: #4CAF50;
            cursor: pointer;
        }
        .edit-btn:hover {
            color: #388E3C;
        }
        .gallery-content {
            padding: 15px;
        }
        .gallery-description {
            margin-top: 10px;
            font-size: 14px;
            color: #333;
        }
        .image-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 5px;
        }
        .image-item {
            width: 100%;
            padding-bottom: 100%;
            position: relative;
            overflow: hidden;
        }
        .image-item img {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        .video-container {
            position: relative;
            width: 100%;
            padding-bottom: 56.25%; /* 16:9比例 */
            background-color: #000;
            overflow: hidden;
        }
        .video-container video {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        .play-button {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 60px;
            height: 60px;
            background-color: rgba(0,0,0,0.5);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            z-index: 10;
        }
        .play-button:before {
            content: '';
            display: block;
            width: 0;
            height: 0;
            border-style: solid;
            border-width: 15px 0 15px 25px;
            border-color: transparent transparent transparent #fff;
            margin-left: 5px;
        }
        /* 全屏查看器样式 */
        .viewer-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: #000;
            z-index: 9999;
            display: none;
            align-items: center;
            justify-content: center;
        }
        .viewer-content {
            position: relative;
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .viewer-image {
            max-width: 100%;
            max-height: 100%;
        }
        .viewer-video {
            width: 100%;
            height: 100%;
            object-fit: contain;
        }
        .viewer-close {
            position: absolute;
            top: 20px;
            right: 20px;
            width: 40px;
            height: 40px;
            background-color: rgba(0,0,0,0.5);
            color: #fff;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            cursor: pointer;
            z-index: 10;
        }
        .viewer-nav {
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            width: 40px;
            height: 40px;
            background-color: rgba(0,0,0,0.5);
            color: #fff;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            cursor: pointer;
            z-index: 10;
        }
        .viewer-prev {
            left: 20px;
        }
        .viewer-next {
            right: 20px;
        }
        /* 上传按钮和遮罩层样式 */
        .upload-btn {
            position: fixed;
            top: 20px;
            right: 20px;
            width: 50px;
            height: 50px;
            background-color: #4CAF50;
            color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            cursor: pointer;
            z-index: 9998;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
        }
        .upload-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
            z-index: 9997;
            display: none;
            align-items: center;
            justify-content: center;
        }
        .upload-options {
            background-color: white;
            border-radius: 10px;
            padding: 30px;
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        .upload-option {
            width: 80px;
            height: 80px;
            margin: 15px;
            background-color: #f0f0f0;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 36px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        .upload-option:hover {
            background-color: #e0e0e0;
        }
        .upload-option span {
            display: block;
            font-size: 14px;
            margin-top: 10px;
            text-align: center;
        }
        /* 图片预览容器样式 */
        .add-image-btn {
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #f5f5f5;
            border: 2px dashed #ddd;
            font-size: 24px;
            color: #999;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .add-image-btn:hover {
            background-color: #e9e9e9;
            color: #666;
        }
        #photoPreviewContainer {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 10px;
            max-height: calc(100vh - 250px);
            overflow-y: auto;
            width: 100%;
        }

        #photoPreviewContainer .image-item {
            width: 100%;
            padding-bottom: 100%;
            position: relative;
            overflow: hidden;
            border-radius: 4px;
            background-color: #f5f5f5;
        }

        #photoPreviewContainer .image-item img {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        /* 加载中状态样式 */
        .image-loading {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: #eee;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        /* 消息遮罩层动画 */
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .delete-btn {
            position: absolute;
            top: 5px;
            right: 5px;
            width: 30px; /* 增大尺寸 */
            height: 30px; /* 增大尺寸 */
            background-color: rgba(255, 0, 0, 0.8); /* 增加不透明度 */
            color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            font-weight: bold;
            font-size: 18px; /* 增大字体 */
            z-index: 100; /* 提高层级 */
            box-shadow: 0 2px 5px rgba(0,0,0,0.3); /* 添加阴影增加可见性 */
        }

        /* 拖动相关样式 */
        .image-item {
            cursor: move; /* 显示移动光标 */
            transition: all 0.2s ease; /* 平滑过渡效果 */
            -webkit-user-select: none; /* 禁止选择文本 */
            -moz-user-select: none;
            -ms-user-select: none;
            user-select: none;
            -webkit-user-drag: element; /* Chrome需要这个属性 */
            -khtml-user-drag: element;
            -moz-user-drag: element;
            -o-user-drag: element;
        }

        /* Chrome特有拖动样式 */
        @media screen and (-webkit-min-device-pixel-ratio:0) {
            .image-item {
                outline: 1px solid transparent; /* 修复Chrome拖动问题 */
            }
            
            .image-item.dragging {
                opacity: 0.5;
                transform: scale(0.95);
                transition: transform 0.2s;
            }
        }
        /* 触摸拖动样式 */
        @media (hover: none) and (pointer: coarse) {
            .image-item {
                touch-action: none; /* 禁止默认触摸行为 */
                -ms-touch-action: none;
            }
            
            .image-item.dragging {
                opacity: 0.7;
                transform: scale(1.05);
                z-index: 100;
            }
        }
        .image-item:hover {
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.3); /* 悬停效果 */
        }

        .image-item.dragging {
            opacity: 0.5; /* 拖动时半透明 */
            transform: scale(1.05); /* 拖动时略微放大 */
            z-index: 100; /* 确保拖动元素在最上层 */
        }

        /* 拖动占位符样式 */
        .image-item-placeholder {
            background-color: rgba(0, 0, 255, 0.1);
            border: 2px dashed #0066ff;
            border-radius: 8px;
        }

        /* 搜索相关样式 */
        .gallery-header-container {
            position: relative;
            text-align: center;
            margin-bottom: 15px;
        }

        .search-icon {
            position: absolute;
            right: 25%;
            top: 50%;
            transform: translateY(-50%);
            font-size: 20px;
            cursor: pointer;
            color: #666;
        }

        .search-box {
            text-align: center;
            margin-bottom: 15px;
        }

        .search-box input {
            padding: 8px;
            width: 60%;
            max-width: 300px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        .search-box button {
            padding: 8px 15px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-left: 5px;
        }
    </style>
</head>
<body>
    <div class="container mt-4">
        <div class="gallery-header-container">
            <h1 class="text-center mb-4">我的画廊</h1>
            <div class="search-icon" onclick="showSearchBox()">🔍</div>
        </div>
        <div id="search-box" class="search-box" style="display: none;">
            <input type="text" id="search-input" placeholder="输入搜索关键词...">
            <button onclick="searchGallery()">搜索</button>
        </div>
        <!-- 添加上传按钮 -->
        <div class="upload-btn" onclick="showUploadOptions()">+</div>
        <div id="gallery-container" style="overflow-y: auto; max-height: calc(100vh - 150px);">
            <div id="gallery-list" class="row">
                <!-- 使用Thymeleaf遍历第一页画廊列表 -->
                <div th:each="gallery : ${galleryList}" class="col-xs-12 gallery-item">
                    <div class="gallery-header">
                        <h3 class="gallery-title" th:text="${gallery.title}"></h3>
                        <div th:if="${gallery.createBy eq currentUser.loginName}" class="edit-btn" th:onclick="editGallery([[${gallery.id}]])">✎编辑</div>
                    </div>
                    <div class="gallery-content">
                        <div class="gallery-media" th:attr="data-id=${gallery.id}, data-type=${gallery.galleryType}">
                            <!-- 媒体内容将动态加载 -->
                        </div>
                        <p class="gallery-description" th:text="${gallery.content ?: '无描述'}"></p>
                    </div>
                </div>
            </div>
            <!-- 加载指示器 -->
            <div id="loading-indicator" style="text-align: center; padding: 20px; display: none;">
                <div style="border: 4px solid #f3f3f3; border-top: 4px solid #3498db; border-radius: 50%; width: 30px; height: 30px; animation: spin 1s linear infinite; margin: 0 auto 10px;"></div>
                <p>加载更多...</p>
            </div>
        </div>
    </div>

    <!-- 图片/视频查看器 -->
    <div id="viewer" class="viewer-overlay">
        <div class="viewer-content">
            <div class="viewer-close" onclick="closeViewer()">&times;</div>
            <div class="viewer-nav viewer-prev" onclick="prevItem()">&#10094;</div>
            <div class="viewer-nav viewer-next" onclick="nextItem()">&#10095;</div>
            <img id="viewer-image" class="viewer-image" src="" alt="">
            <video id="viewer-video" class="viewer-video" controls></video>
        </div>
    </div>

    <!-- 上传选项遮罩层 -->
    <div id="uploadOverlay" class="upload-overlay">
        <div class="upload-options">
            <div class="upload-option" onclick="uploadPhoto()">
                📷
                <span>照片</span>
            </div>
            <div class="upload-option" onclick="uploadVideo()">
                🎥
                <span>视频</span>
            </div>
        </div>
    </div>

    <!-- 图片选择预览遮罩层 -->
    <div id="photoPreviewOverlay" class="upload-overlay">
        <div class="upload-options" style="width: 100%; height: 100%; max-width: 500px; padding: 20px;">
            <div style="display: flex; justify-content: space-between; align-items: center; width: 100%; margin-bottom: 15px;">
                <button onclick="closePreview()" style="background: transparent; border: none; font-size: 24px;">&times;</button>
                <div style="display: flex; gap: 30px;">
                    <button id="deleteGalleryBtn" onclick="deleteGallery()" style="background-color: #f44336; color: white; border: none; padding: 8px 16px; border-radius: 4px; display: none;">删除</button>
                    <button id="saveGalleryBtn" onclick="saveGallery()" style="background-color: #4CAF50; color: white; border: none; padding: 8px 16px; border-radius: 4px;">保存</button>
                </div>
            </div>

            <!-- 画廊信息表单 -->
            <div style="margin-bottom: 20px; width: 100%;">
                <label for="galleryDescription" style="display: block; margin-bottom: 5px; font-weight: bold;">画廊描述</label>
                <textarea id="galleryDescription" placeholder="请输入画廊描述" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; min-height: 80px;"></textarea>

                <label for="galleryRecordDate" style="display: block; margin-bottom: 5px; font-weight: bold;">记录日期</label>
                <input type="date" id="galleryRecordDate" placeholder="请选择记录日期" style="width: 100%; padding: 10px; margin-bottom: 10px; border: 1px solid #ddd; border-radius: 4px;">

                <label for="galleryShareType" style="display: block; margin-bottom: 5px; font-weight: bold;">是否公开</label>
                <select id="galleryShareType" style="width: 100%; padding: 10px; margin-bottom: 10px; border: 1px solid #ddd; border-radius: 4px;">
                    <option value="2">是</option>
                    <option value="1">否</option>
                </select>
                <input type="text" id="galleryTitle" placeholder="画廊标题" style="display: none; width: 100%; padding: 10px; margin-bottom: 10px; border: 1px solid #ddd; border-radius: 4px;">
            </div>

            <!-- 已选图片计数 -->
            <div id="selectedCount" style="margin-bottom: 10px; font-size: 14px;">已选择: 0 张图片</div>

            <!-- 图片预览容器 -->
            <div id="photoPreviewContainer">
            </div>
        </div>
    </div>

    <!-- 隐藏的文件输入元素 -->
    <input type="file" id="photoInput" multiple accept="image/*" style="display: none;">
    <input type="file" id="videoInput" accept="video/*" style="display: none;">

    <!-- 消息提示遮罩层 -->
    <div id="loadingOverlay" class="upload-overlay" style="display: none; justify-content: center; align-items: center; background-color: rgba(0, 0, 0, 0.7);">
        <div style="text-align: center; background-color: white; padding: 30px; border-radius: 8px; max-width: 300px;">
            <div style="border: 4px solid #f3f3f3; border-top: 4px solid #3498db; border-radius: 50%; width: 40px; height: 40px; animation: spin 1s linear infinite; margin: 0 auto 15px;"></div>
            <p id="loadingMessage">加载中...</p>
        </div>
    </div>


    <th:block th:include="include :: footer" />
    <script th:inline="javascript">
        let galleryList = [[${galleryList}]];
        let currentGallery = null;
        let editGalleryId = null;
        let currentFiles = [];
        let currentIndex = 0;
        let isViewerOpen = false;
        // 分页参数
        let currentPage = 1;
        const pageSize = 10;
        let isLoading = false;
        let hasMoreGalleries = true;
        // 添加当前登录用户信息
        let currentUser = [[${currentUser.loginName}]];
        // 新增：用于存储编辑开始时的文件ID列表
        let originalFileIds = [];
        // 记录搜索关键次
        let keyword = '';

        // 页面加载完成后初始化
        $(document).ready(function() {
            // 加载每个画廊的媒体内容
            loadVisibleGalleryMedia();

            // 添加滚动事件监听
            const galleryContainer = document.getElementById('gallery-container');
            galleryContainer.addEventListener('scroll', handleScroll);
        });

        // 处理滚动事件
        function handleScroll() {
            // 无论是否加载更多，都先加载可见的媒体内容
            loadVisibleGalleryMedia();

            // 然后检查是否需要加载更多画廊
            if (isLoading || !hasMoreGalleries) return;

            const galleryContainer = document.getElementById('gallery-container');
            const { scrollTop, scrollHeight, clientHeight } = galleryContainer;

            // 当滚动到距离底部20px时加载更多
            if (scrollHeight - scrollTop - clientHeight < 20) {
                loadMoreGalleries();
            }
        }

        // 加载更多画廊fcurrentPage
        function loadMoreGalleries() {
            isLoading = true;
            document.getElementById('loading-indicator').style.display = 'block';
            currentPage++;

            $.ajax({
                url: `/file/gallery/mobile/list`,
                type: 'POST',
                data: {
                    "pageNum": currentPage,
                    "pageSize": pageSize,
                    "keyword": keyword,
                },
                success: function(res) {
                    isLoading = false;
                    document.getElementById('loading-indicator').style.display = 'none';

                    if (res.code === 0 && res.rows.length > 0) {
                        const galleryListElement = document.getElementById('gallery-list');

                        // 添加新画廊到列表
                        res.rows.forEach(gallery => {
                            galleryList.push(gallery);
                            const galleryItem = createGalleryItem(gallery);
                            galleryListElement.appendChild(galleryItem);
                        });

                        // 加载新添加画廊的媒体内容
                        loadVisibleGalleryMedia();

                        // 关键修改：当返回的记录数小于pageSize时，标记为没有更多数据
                        if (res.rows.length < pageSize) {
                            hasMoreGalleries = false;
                        }
                    } else {
                        // 没有更多画廊
                        hasMoreGalleries = false;
                    }
                },
                error: function() {
                    isLoading = false;
                    document.getElementById('loading-indicator').style.display = 'none';
                    currentPage--;
                    showNotification('加载更多画廊失败，请重试');
                }
            });
        }

        // 创建画廊项DOM元素
        function createGalleryItem(gallery) {
            const galleryItem = document.createElement('div');
            galleryItem.className = 'col-xs-12 gallery-item';
            // 检查是否为当前用户创建的画廊
            const isOwner = gallery.createBy === currentUser;
            galleryItem.innerHTML = `
                <div class="gallery-header" style="position: relative;">
                    <h3 class="gallery-title">${gallery.title}</h3>
                    ${isOwner ? '<div class="edit-btn" onclick="editGallery(\'' + gallery.id + '\')">✎编辑</div>' : ''}
                </div>
                <div class="gallery-content">
                    <div class="gallery-media" data-id="${gallery.id}" data-type="${gallery.galleryType}">
                        <!-- 媒体内容将动态加载 -->
                    </div>
                    <p class="gallery-description">${gallery.content || '无描述'}</p>
                </div>
            `;
            return galleryItem;
        }

        // 加载可见的画廊媒体内容
        function loadVisibleGalleryMedia() {
            const galleryContainer = document.getElementById('gallery-container');
            const containerTop = galleryContainer.getBoundingClientRect().top;
            const containerBottom = galleryContainer.getBoundingClientRect().bottom;

            $('.gallery-media').each(function() {
                const mediaElement = $(this);
                if (!mediaElement.data('loaded')) {
                    const elementTop = this.getBoundingClientRect().top;
                    const elementBottom = this.getBoundingClientRect().bottom;

                    // 如果元素在可见区域内
                    if (elementBottom > containerTop && elementTop < containerBottom) {
                        const galleryId = mediaElement.data('id');
                        const galleryType = mediaElement.data('type');
                        loadGalleryMedia(galleryId, galleryType, mediaElement);
                        mediaElement.data('loaded', true);
                    }
                }
            });
        }

        // 显示上传选项
        function showUploadOptions() {
            document.getElementById('uploadOverlay').style.display = 'flex';
            // 隐藏上传按钮
            document.querySelector('.upload-btn').style.display = 'none';
        }

        // 隐藏上传选项
        function hideUploadOptions() {
            document.getElementById('uploadOverlay').style.display = 'none';
            // 显示上传按钮
            document.querySelector('.upload-btn').style.display = 'flex';
        }

        // 上传照片
        function uploadPhoto() {
            hideUploadOptions();
            // 触发文件选择对话框
            document.getElementById('photoInput').click();
            editGalleryId = null;
        }

        // 上传视频
        function uploadVideo() {
            hideUploadOptions();
            // 触发文件选择对话框
            document.getElementById('videoInput').click();
            editGalleryId = null;
        }

        // 处理照片选择
        document.getElementById('photoInput').addEventListener('change', handlePhotoSelection);
        // 处理视频选择
        document.getElementById('videoInput').addEventListener('change', handleVideoSelection);

        // 创建删除按钮的复用函数
        function createDeleteButton(previewContainer, previewItem, index) {
            const deleteBtn = document.createElement('div');
            deleteBtn.className = 'delete-btn';
            deleteBtn.innerHTML = '×';
            // 添加z-index确保按钮在最上层
            deleteBtn.style.zIndex = '100';
            
            // 定义删除函数
            const deleteImage = function() {
                console.log("deleteBtn clicked");
                currentFiles.splice(index, 1);
                previewContainer.removeChild(previewItem);
                updateSelectedCount(currentFiles.length);
                // 确保不会触发上传
                return false;
            };
            
            // 绑定点击事件
            deleteBtn.onclick = function(e) {
                e.stopPropagation();
                e.preventDefault();  // 添加阻止默认行为
                deleteImage();
                return false;  // 确保事件不会继续传播
            };
            
            // 添加触摸事件处理
            deleteBtn.addEventListener('touchstart', function(e) {
                e.stopPropagation();
                e.preventDefault();  // 添加阻止默认行为
                isDragging = false;
                touchStartTime = Date.now(); // 记录触摸开始时间
            });
            
            deleteBtn.addEventListener('touchmove', function(e) {
                e.stopPropagation();
                e.preventDefault();  // 添加阻止默认行为
            });
            
            deleteBtn.addEventListener('touchend', function(e) {
                e.stopPropagation();
                e.preventDefault();  // 添加阻止默认行为
                
                // 检查触摸时间，区分点击和长按
                const touchEndTime = Date.now();
                if (touchEndTime - touchStartTime < 200) {
                    // 直接调用删除函数，而不是触发点击事件
                    deleteImage();
                }
            });
            
            return deleteBtn;
        }

        // 照片选择处理函数
        function handlePhotoSelection(event) {
            const files = event.target.files;
            if (files.length === 0) return;

            // 获取预览容器
            const previewContainer = document.getElementById('photoPreviewContainer');
            // 图片样式
            previewContainer.style.maxHeight = 'calc(100vh - 250px)';
            previewContainer.style.overflowY = 'auto';

            // 检查是否处于编辑模式
            const isEditMode = !!editGalleryId;
            
            // 如果不是编辑模式，则清空预览容器和表单项
            if (!isEditMode) {
                previewContainer.innerHTML = '';
                // 清空表单项
                resetForm();
                // 显示预览遮罩层
                document.getElementById('photoPreviewOverlay').style.display = 'flex';
                // 隐藏上传按钮
                document.querySelector('.upload-btn').style.display = 'none';
                // 重置计数器
                updateSelectedCount(0);
                // 如果不是编辑模式，则隐藏删除按钮
                document.getElementById('deleteGalleryBtn').style.display = 'none';
            } else {
                // 编辑模式下，移除新增按钮（稍后会重新添加）
                const addButton = previewContainer.querySelector('.add-image-btn');
                if (addButton) {
                    previewContainer.removeChild(addButton);
                }
            }

            // 遍历选中的文件并预览
            Array.from(files).forEach((file, index) => {
                const reader = new FileReader();

                // 创建预览项
                const previewItem = document.createElement('div');
                previewItem.className = 'image-item';
                previewItem.setAttribute('data-index', isEditMode ? currentFiles.length + index : index);

                // 添加加载中状态
                const loadingIndicator = document.createElement('div');
                loadingIndicator.className = 'image-loading';
                loadingIndicator.textContent = '加载中...';
                previewItem.appendChild(loadingIndicator);

                // 选中状态标记
                const selectMarker = document.createElement('div');
                selectMarker.style.position = 'absolute';
                selectMarker.style.top = '5px';
                selectMarker.style.right = '5px';
                selectMarker.style.width = '20px';
                selectMarker.style.height = '20px';
                selectMarker.style.backgroundColor = 'rgba(76, 175, 80, 0.7)';
                selectMarker.style.borderRadius = '50%';
                selectMarker.style.display = 'flex';
                selectMarker.style.alignItems = 'center';
                selectMarker.style.justifyContent = 'center';
                selectMarker.style.color = 'white';
                selectMarker.style.fontSize = '12px';
                selectMarker.style.fontWeight = 'bold';
                selectMarker.textContent = isEditMode ? currentFiles.length + index + 1 : index + 1;
                selectMarker.style.display = 'none'; // 初始隐藏

                previewItem.appendChild(selectMarker);
                previewContainer.appendChild(previewItem);

                // 添加删除按钮（编辑模式下）
                if (isEditMode) {
                    // 原代码被替换为:
                    const deleteBtn = createDeleteButton(previewContainer, previewItem, index);
                    previewItem.appendChild(deleteBtn);
                }

                reader.onloadstart = function() {
                    loadingIndicator.textContent = '加载中...';
                };

                reader.onload = function(e) {
                    // 移除加载状态
                    loadingIndicator.remove();
                    selectMarker.style.display = 'flex'; // 显示选中标记

                    const img = document.createElement('img');
                    img.src = e.target.result;
                    img.style.width = '100%';
                    img.style.height = '100%';
                    img.style.objectFit = 'cover';
                    // 添加图片加载错误处理
                    img.onerror = function() {
                        console.error('图片加载失败:', e.target.result);
                        // 使用系统默认占位图
                        this.src = 'data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%22100%25%22%20height%3D%22100%25%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Crect%20width%3D%22100%25%22%20height%3D%22100%25%22%20fill%3D%22%23f5f5f5%22%2F%3E%3Ctext%20x%3D%2250%25%22%20y%3D%2250%25%22%20dominant-baseline%3D%22middle%22%20text-anchor%3D%22middle%22%20fill%3D%22%23999%22%20font-size%3D%2214%22%3E图片加载失败%3C%2Ftext%3E%3C%2Fsvg%3E';
                    };

                    previewItem.appendChild(img);

                    // 更新计数
                    if (isEditMode) {
                        // 编辑模式下，将新文件添加到currentFiles
                        const fileObj = {
                            file: file,
                            tempId: 'temp_' + Date.now() + '_' + Math.floor(Math.random() * 1000) // 添加临时ID
                        };
                        currentFiles.push(fileObj);
                        updateSelectedCount(currentFiles.length);
                    } else {
                        updateSelectedCount(files.length);
                    }
                };

                reader.onerror = function() {
                    loadingIndicator.textContent = '加载失败';
                    console.error('文件读取失败:', file.name);
                };

                reader.readAsDataURL(file);
            });

            // 编辑模式下，重新添加新增按钮
            if (isEditMode) {
                addAddButton();
            }

            // 获取第一个文件的日期并设置到记录日期字段（仅新建模式）
            if (!isEditMode) {
                const firstFile = files[0];
                if (firstFile.lastModified){
                    // 获取文件的最后修改日期
                    const fileDate = new Date(firstFile.lastModified);
                    // 格式化日期为 YYYY-MM-DD 格式
                    const formattedDate = `${fileDate.getFullYear()}-${String(fileDate.getMonth() + 1).padStart(2, '0')}-${String(fileDate.getDate()).padStart(2, '0')}`;
                    // 设置记录日期字段的值
                    document.getElementById('galleryRecordDate').value = formattedDate;
                }
            }

            // 添加新增按钮的辅助函数
            function addAddButton() {
                // 先移除可能存在的按钮
                const existingButton = previewContainer.querySelector('.add-image-btn');
                if (existingButton) {
                    previewContainer.removeChild(existingButton);
                }
                // 创建并添加新按钮
                const addButton = document.createElement('div');
                addButton.className = 'image-item add-image-btn';
                addButton.innerHTML = '+';
                addButton.onclick = function() {
                    document.getElementById('photoInput').click();
                };
                previewContainer.appendChild(addButton);
            }
        }

        // 视频选择处理函数
        function handleVideoSelection(event) {
            const files = event.target.files;
            if (files.length === 0) return;

            // 清空预览容器
            const previewContainer = document.getElementById('photoPreviewContainer');
            previewContainer.innerHTML = '';
            // 视频样式
            previewContainer.style.maxHeight = 'none';
            previewContainer.style.overflowY = 'visible';
                            
            // 调用通用方法重置表单
            resetForm();

            // 显示预览遮罩层
            document.getElementById('photoPreviewOverlay').style.display = 'flex';
            // 如果不是编辑模式，则隐藏删除按钮
            document.getElementById('deleteGalleryBtn').style.display = 'none';

            // 隐藏上传按钮
            document.querySelector('.upload-btn').style.display = 'none';

            // 更新计数文本
            document.getElementById('selectedCount').textContent = '已选择: 1 个视频';

            // 处理第一个视频文件
            const file = files[0];
            const reader = new FileReader();

            // 创建预览项
            const previewItem = document.createElement('div');
            previewItem.className = 'video-preview-item';
            previewItem.style.width = '100%';
            previewItem.style.height = '100px';
            previewItem.style.aspectRatio = '16/9';
            previewItem.style.position = 'relative';
            previewItem.style.backgroundColor = '#000';
            previewItem.style.borderRadius = '8px';

            // 添加加载中状态
            const loadingIndicator = document.createElement('div');
            loadingIndicator.className = 'image-loading';
            loadingIndicator.textContent = '加载中...';
            loadingIndicator.style.color = 'white';
            loadingIndicator.style.display = 'flex';
            loadingIndicator.style.alignItems = 'center';
            loadingIndicator.style.justifyContent = 'center';
            loadingIndicator.style.height = '100%';
            previewItem.appendChild(loadingIndicator);

            previewContainer.appendChild(previewItem);

            reader.onloadstart = function() {
                loadingIndicator.textContent = '加载中...';
            };

            reader.onload = function(e) {
                // 移除加载状态
                loadingIndicator.remove();

                // 创建视频元素
                const video = document.createElement('video');
                video.src = e.target.result;
                video.style.width = '100%';
                video.style.height = '100%';
                video.style.objectFit = 'contain'; // 添加这一行确保视频完整显示
                video.controls = true;
                video.preload = 'metadata';

                previewItem.appendChild(video);
            };

            reader.onerror = function() {
                loadingIndicator.textContent = '加载失败';
                console.error('文件读取失败:', file.name);
            };

            reader.readAsDataURL(file);

            // 获取视频文件的日期并设置到记录日期字段
            if (file.lastModified){
                const fileDate = new Date(file.lastModified);
                const formattedDate = `${fileDate.getFullYear()}-${String(fileDate.getMonth() + 1).padStart(2, '0')}-${String(fileDate.getDate()).padStart(2, '0')}`;
                document.getElementById('galleryRecordDate').value = formattedDate;
            }
        }


        // 更新选中图片计数
        function updateSelectedCount(count) {
            document.getElementById('selectedCount').textContent = `已选择: ${count} 张图片`;
        }

        // 关闭预览
        function closePreview() {
            document.getElementById('photoPreviewOverlay').style.display = 'none';
            // 重置文件输入，以便能重复选择同一批文件
            document.getElementById('photoInput').value = '';
            document.getElementById('videoInput').value = '';
            // 显示上传按钮
            document.querySelector('.upload-btn').style.display = 'flex';
        }

        // 保存画廊：新增、编辑的保存
        function saveGallery() {
            const recordDate = document.getElementById('galleryRecordDate').value;
            if (!recordDate) {
                showNotification('请选择记录日期');
                return;
            }

            // 自动将记录日期赋值给画廊标题
            const galleryTitle = document.getElementById('galleryTitle');
            galleryTitle.value = recordDate;
            const title = galleryTitle.value.trim();
            
            const shareType = document.getElementById('galleryShareType').value;
            const content = document.getElementById('galleryDescription').value.trim();
            
            // 判断是新建还是编辑
            const galleryId = editGalleryId;

            // 创建FormData对象
            const formData = new FormData();
            formData.append('title', title);
            formData.append('recordDate', recordDate);
            formData.append('shareType', shareType);
            formData.append('content', content);
            
            if (galleryId) {
                // 编辑操作
                // 增加currentFiles不能为空的校验
                if (!currentFiles || currentFiles.length === 0) {
                    showNotification('画廊内容不能为空');
                    return;
                }
                
                formData.append('id', galleryId);
                
                // 计算并添加删除的文件ID
                const currentFileIds = currentFiles.filter(file => file.id).map(file => file.id);
                const deletedFileIds = originalFileIds.filter(id => !currentFileIds.includes(id));
                    
                if (deletedFileIds.length > 0) {
                    formData.append('deletedFileIds', deletedFileIds.join(','));
                }
                
                // 添加排序信息 - 包含所有文件的顺序
                const fullSortedOrder = currentFiles.map(file => {
                    // 既有文件使用id，新文件使用tempId
                    return file.id || file.tempId;
                });
                formData.append('fullSortedOrder', fullSortedOrder.join(','));

                // 添加新选择的图片文件（编辑模式）
                const newFiles = currentFiles.filter(file => !file.id && file.file);
                newFiles.forEach(file => {
                    formData.append('files', file.file);
                });
            } else {
                // 如果是新建操作
                const photoFiles = document.getElementById('photoInput').files;
                const videoFiles = document.getElementById('videoInput').files;
                let files = [];
                let isVideo = false;
                // 检查是图片还是视频
                if (photoFiles.length > 0) {
                    files = photoFiles;
                } else if (videoFiles.length > 0) {
                    files = videoFiles;
                    isVideo = true;
                } else if (!galleryId) {
                    // 如果是新建且没有选择文件，则提示错误
                    showNotification('请选择图片或视频');
                    return;
                }
                formData.append('isVideo', isVideo);
                // 添加文件
                Array.from(files).forEach(file => {
                    formData.append('files', file);
                });
            }
            
            // 显示加载中
            showLoading('保存中...');
            
            // 发送请求
            const url = galleryId ? '/file/gallery/mobile/update' : '/file/gallery/mobile/save';
            $.ajax({
                url: url,
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(res) {
                    hideLoading();
                    if (res.code === 0) {
                        showNotification('保存成功');
                        closePreview();
                        // 调用通用方法重置表单
                        resetForm();
                        currentFiles = [];
                        originalFileIds = []; // 重置原始文件ID列表
                        
                        // 刷新画廊列表
                        location.reload();
                    } else {
                        showNotification(res.msg || '保存失败');
                    }
                },
                error: function() {
                    hideLoading();
                    showNotification('保存失败，请重试');
                }
            });
        }

        // 重置表单的通用方法
        function resetForm() {
            document.getElementById('galleryTitle').value = '';
            document.getElementById('galleryRecordDate').value = '';
            document.getElementById('galleryShareType').value = '2';
            document.getElementById('galleryDescription').value = '';
        }

        // 显示加载提示
        function showLoading(message) {
            const loadingOverlay = document.getElementById('loadingOverlay');
            const loadingMessage = document.getElementById('loadingMessage');
            loadingMessage.textContent = message || '加载中...';
            loadingOverlay.style.display = 'flex';
        }

        // 隐藏加载提示
        function hideLoading() {
            document.getElementById('loadingOverlay').style.display = 'none';
        }

        // 显示非阻塞式通知
        function showNotification(message, duration = 3000) {
            // 检查是否已存在通知元素
            let notification = document.getElementById('notification');
            if (!notification) {
                notification = document.createElement('div');
                notification.id = 'notification';
                notification.style.position = 'fixed';
                notification.style.top = '20px';
                notification.style.left = '50%';
                notification.style.transform = 'translateX(-50%)';
                notification.style.backgroundColor = 'rgba(0, 0, 0, 0.7)';
                notification.style.color = 'white';
                notification.style.padding = '10px 20px';
                notification.style.borderRadius = '4px';
                notification.style.zIndex = '9999';
                notification.style.maxWidth = '80%';
                document.body.appendChild(notification);
            }

            notification.textContent = message;
            notification.style.display = 'block';

            // 自动隐藏
            setTimeout(() => {
                notification.style.display = 'none';
            }, duration);
        }

        // 点击遮罩层空白区域关闭
        document.getElementById('uploadOverlay').addEventListener('click', function(e) {
            if (e.target === this) {
                hideUploadOptions();
            }
        });

        document.getElementById('photoPreviewOverlay').addEventListener('click', function(e) {
            if (e.target === this) {
                closePreview();
            }
        });

        // 加载画廊媒体内容
        function loadGalleryMedia(galleryId, galleryType, container) {
            // 显示加载状态
            container.html('<div class="image-loading" style="height: 150px;">加载中...</div>');

            $.ajax({
                url: `/file/gallery/mobile/files/${galleryId}/${galleryType}`,
                type: 'GET',
                success: function(res) {
                    if (res.code === 0) {
                        const files = res.data;
                        container.empty();

                        if (galleryType === 1) {
                            // 图片画廊
                            const imageGrid = $('<div class="image-grid"></div>');
                            // 最多显示9张图片
                            const displayFiles = files.slice(0, 9);

                            displayFiles.forEach((file, index) => {
                                const imageItem = $(`
                                    <div class="image-item" onclick="openImageViewer('${galleryId}', ${galleryType}, ${index})">
                                        <img src="${file.url || file.thUrl}" alt="图片 ${index + 1}">
                                    </div>
                                `);
                                imageGrid.append(imageItem);
                            });

                            container.append(imageGrid);
                        } else if (galleryType === 2) {
                            // 视频画廊
                            const videoContainer = $('<div class="video-container"></div>');
                            const videoElement = $(`
                                <video src="${files[0].url}" poster="${files[0].thUrl || '/img/video-placeholder.jpg'}" onclick="openVideoViewer('${galleryId}', ${galleryType})"></video>
                                <div class="play-button" onclick="openVideoViewer('${galleryId}', ${galleryType})"></div>
                            `);
                            videoContainer.append(videoElement);
                            container.append(videoContainer);
                        }
                    } else {
                        container.html('<p class="text-danger">加载媒体失败</p>');
                    }
                },
                error: function() {
                    container.html('<p class="text-danger">网络错误</p>');
                }
            });
        }

        // 打开图片查看器
        function openImageViewer(galleryId, galleryType, index) {
            currentGallery = galleryList.find(g => g.id === galleryId);
            currentIndex = index;

            // 加载所有文件
            $.ajax({
                url: `/file/gallery/mobile/files/${galleryId}/${galleryType}`,
                type: 'GET',
                success: function(res) {
                    if (res.code === 0) {
                        currentFiles = res.data;
                        isViewerOpen = true;

                        const viewer = $('#viewer');
                        const viewerImage = $('#viewer-image');
                        const viewerVideo = $('#viewer-video');

                        // 显示图片查看器，隐藏视频
                        viewerImage.show();
                        viewerVideo.hide();
                        viewerVideo[0].pause();

                        // 设置当前图片
                        viewerImage.attr('src', currentFiles[currentIndex].url);

                        // 显示查看器
                        viewer.css('display', 'flex');
                    }
                }
            });
        }

        // 打开视频查看器
        function openVideoViewer(galleryId, galleryType) {
            currentGallery = galleryList.find(g => g.id === galleryId);

            // 加载所有文件
            $.ajax({
                url: `/file/gallery/mobile/files/${galleryId}/${galleryType}`,
                type: 'GET',
                success: function(res) {
                    if (res.code === 0) {
                        currentFiles = res.data;
                        currentIndex = 0;
                        isViewerOpen = true;

                        const viewer = $('#viewer');
                        const viewerImage = $('#viewer-image');
                        const viewerVideo = $('#viewer-video');

                        // 显示视频查看器，隐藏图片
                        viewerImage.hide();
                        viewerVideo.show();

                        // 设置当前视频
                        viewerVideo.attr('src', currentFiles[currentIndex].url);
                        viewerVideo[0].load(); // 确保视频已加载

                        // 尝试播放视频
                        try {
                            viewerVideo[0].play();
                        } catch (error) {
                            console.error('视频播放失败:', error);
                            // 如果自动播放失败，提示用户点击播放
                            alert('视频自动播放失败，请点击播放按钮');
                        }

                        // 显示查看器
                        viewer.css('display', 'flex');
                    }
                }
            });
        }

        // 关闭查看器
        function closeViewer() {
            const viewer = $('#viewer');
            const viewerVideo = $('#viewer-video');

            viewerVideo[0].pause();
            viewer.css('display', 'none');
            isViewerOpen = false;
        }

        // 显示搜索框
        function showSearchBox() {
            const searchBox = document.getElementById('search-box');
            const searchInput = document.getElementById('search-input'); // 获取搜索输入框
            searchBox.style.display = searchBox.style.display === 'none' ? 'block' : 'none';
            if (searchBox.style.display === 'block') {
                searchInput.focus(); // 当搜索框显示时，将光标聚焦到输入框
            }
        }

        // 搜索画廊
        function searchGallery() {
            const searchInput = document.getElementById('search-input');
            keyword = searchInput.value.trim();
            
            // 可以为空，查询全部
            // if (!keyword) {
            //     showNotification('请输入搜索关键词');
            //     return;
            // }

            // 显示加载中
            showLoading('搜索中...');

            // 发送搜索请求到后端API
            $.ajax({
                url: `/file/gallery/mobile/search`,
                type: 'GET',
                data: { keyword: keyword },
                success: function(res) {
                    hideLoading();
                    if (res.code === 0) {
                        // 更新画廊列表
                        const galleryListContainer = document.getElementById('gallery-list');
                        galleryListContainer.innerHTML = '';

                        // 清空当前画廊列表
                        window.galleryList = [];

                        // 添加搜索结果到画廊列表
                        res.rows.forEach(gallery => {
                            window.galleryList.push(gallery);

                            // 创建画廊项HTML
                            const galleryItem = $(`
                                <div class="col-xs-12 gallery-item">
                                    <div class="gallery-header">
                                        <h3 class="gallery-title">${gallery.title}</h3>
                                        ${gallery.createBy === currentUser.loginName ? 
                                            `<div class="edit-btn" onclick="editGallery(${gallery.id})">✎编辑</div>` : ''}
                                    </div>
                                    <div class="gallery-content">
                                        <div class="gallery-media" data-id="${gallery.id}" data-type="${gallery.galleryType}">
                                            <!-- 媒体内容将动态加载 -->
                                        </div>
                                        <p class="gallery-description">${gallery.content || '无描述'}</p>
                                    </div>
                                </div>
                            `);

                            galleryListContainer.appendChild(galleryItem[0]);
                        });

                        // 加载可见画廊媒体
                        loadVisibleGalleryMedia();
                    } else {
                        showNotification(res.msg || '搜索失败');
                    }
                },
                error: function() {
                    hideLoading();
                    showNotification('搜索失败，请重试');
                }
            });
        }



        // 拖动排序相关变量
        let draggedItem = null;
        let dragIndex = -1;
        // 触摸事件变量
        let touchStartX = 0;
        let touchStartY = 0;
        let isDragging = false;
        let touchDraggedItem = null;
        let touchDragIndex = -1;
        let touchEndX = 0;

        // 拖动开始
        function handleDragStart(e) {
            console.log("handleDragStart triggered");
            draggedItem = this;
            dragIndex = parseInt(this.getAttribute('data-index'));
            e.dataTransfer.effectAllowed = 'move';
            
            // 关键修复：Chrome需要明确设置text/html格式数据
            e.dataTransfer.setData('text/plain', dragIndex.toString());
            e.dataTransfer.setData('text/html', this.outerHTML);
            
            // 添加拖动样式
            setTimeout(() => {
                this.classList.add('dragging');
            }, 0);
            
            // 阻止默认行为
            return false;
        }

        // 拖动经过
        function handleDragOver(e) {
            if (e.preventDefault) {
                e.preventDefault();
            }
            // 关键修复：明确设置dropEffect
            e.dataTransfer.dropEffect = 'move';
            
            // 添加视觉反馈
            if (this !== draggedItem) {
                const rect = this.getBoundingClientRect();
                const mouseY = e.clientY;
                const threshold = rect.top + rect.height / 2;
            }
            
            return false;
        }

        // 拖动进入
        function handleDragEnter(e) {
            if (e.preventDefault) {
                e.preventDefault();
            }
            if (this !== draggedItem) {
                this.classList.add('image-item-placeholder');
            }
        }

        // 拖动离开
        function handleDragLeave() {
            this.classList.remove('image-item-placeholder');
        }

        // 放置
        function handleDrop(e) {
            if (e.stopPropagation) {
                e.stopPropagation();
            }
            if (e.preventDefault) {
                e.preventDefault();
            }
            
            // 移除所有占位符样式
            document.querySelectorAll('.image-item').forEach(item => {
                item.classList.remove('image-item-placeholder');
            });
            
            if (draggedItem && draggedItem !== this) {
                const dropIndex = parseInt(this.getAttribute('data-index'));
                
                // 更新数据顺序
                const draggedFile = currentFiles[dragIndex];
                currentFiles.splice(dragIndex, 1);
                currentFiles.splice(dropIndex, 0, draggedFile);
                
                // 重新渲染预览
                renderPreview();
            }
            
            return false;
        }

        // 拖动结束
        function handleDragEnd() {
            console.log("handleDragEnd triggered");
            this.classList.remove('dragging'); // 移除拖动样式
            draggedItem = null;
            dragIndex = -1;
        }

        // 触摸开始
        function handleTouchStart(e) {
            console.log("handleTouchStart");
            // 防止触摸事件被放大或滚动干扰
            e.preventDefault();
            
            touchDraggedItem = this;
            touchDragIndex = parseInt(this.getAttribute('data-index'));
            
            // 记录触摸起始位置
            const touch = e.touches[0];
            touchStartX = touch.clientX;
            touchStartY = touch.clientY;
            
            // 添加拖动样式
            setTimeout(() => {
                this.classList.add('dragging');
                isDragging = true;
            }, 100); // 轻微延迟，避免点击误判为拖动
        }

        // 触摸移动
        function handleTouchMove(e) {
            console.log("handleTouchMove");
            if (!isDragging) return;
            console.log("handleTouchMove2");
            
            e.preventDefault();
            
            // 计算移动距离
            const touch = e.touches[0];
            const touchX = touch.clientX;
            const touchY = touch.clientY;
            
            // 获取当前触摸位置下的元素
            const targetElement = document.elementFromPoint(touchX, touchY);
            console.log("ok");
            console.log(targetElement);

            // 修复：查找包含image-item类的元素，无论是当前元素还是其父元素
            let dropTarget = targetElement;
            while (dropTarget && !dropTarget.classList.contains('image-item')) {
                dropTarget = dropTarget.parentElement;
            }

            // 如果目标元素是图片项且不是正在拖动的项
            if (dropTarget && dropTarget !== touchDraggedItem) {
                console.log("go...")
                console.log(dropTarget)
                // 计算放置位置 - 修复：使用dropTarget而不是targetElement
                const dropIndex = parseInt(dropTarget.getAttribute('data-index'));
                
                // 修复：检查索引是否有效
                if (!isNaN(dropIndex) && dropIndex >= 0 && dropIndex < currentFiles.length && touchDragIndex >= 0 && touchDragIndex < currentFiles.length) {
                    // 更新数据顺序
                    const draggedFile = currentFiles[touchDragIndex];
                    currentFiles.splice(touchDragIndex, 1);
                    currentFiles.splice(dropIndex, 0, draggedFile);
                    
                    // 更新拖动索引
                    touchDragIndex = dropIndex;
                    
                    // 重新渲染预览
                    renderPreview();
                } else {
                    console.error('无效的索引值: touchDragIndex=', touchDragIndex, ', dropIndex=', dropIndex);
                }
            }
        }

        // 触摸结束
        function handleTouchEnd(e) {
             console.log("handleTouchEnd");
            if (!isDragging) return;
             console.log("handleTouchEnd2");
            
            e.preventDefault();
            
            // 移除拖动样式
            if (touchDraggedItem) {
                touchDraggedItem.classList.remove('dragging');
            }
            
            // 重置状态
            isDragging = false;
            touchDraggedItem = null;
            touchDragIndex = -1;
        }

        // 统一渲染预览函数 - 抽取自handleDrop
        function renderPreview() {
            console.log("renderPreview");
            console.log(currentFiles);

            const previewContainer = document.getElementById('photoPreviewContainer');
            previewContainer.innerHTML = '';
            
            currentFiles.forEach((file, index) => {
                const previewItem = document.createElement('div');
                previewItem.className = 'image-item';
                previewItem.setAttribute('data-index', index);
                previewItem.setAttribute('draggable', 'true');
                
                // 添加事件监听器
                previewItem.addEventListener('dragstart', handleDragStart.bind(previewItem));
                previewItem.addEventListener('dragover', handleDragOver.bind(previewItem));
                previewItem.addEventListener('dragenter', handleDragEnter.bind(previewItem));
                previewItem.addEventListener('dragleave', handleDragLeave.bind(previewItem));
                previewItem.addEventListener('drop', handleDrop.bind(previewItem));
                previewItem.addEventListener('dragend', handleDragEnd.bind(previewItem));
                previewItem.addEventListener('touchstart', handleTouchStart.bind(previewItem));
                previewItem.addEventListener('touchmove', handleTouchMove.bind(previewItem));
                previewItem.addEventListener('touchend', handleTouchEnd.bind(previewItem));
                
                // 添加删除按钮
                const deleteBtn = createDeleteButton(previewContainer, previewItem, index);
                previewItem.appendChild(deleteBtn);
                
                // 创建图片元素
                const img = document.createElement('img');
                console.log("file");
                console.log(file);
                
                // 修复：检查file是否存在
                if (file) {
                    img.src = file.url || file.thUrl || (file.file ? URL.createObjectURL(file.file) : '');
                } else {
                    console.error('文件对象未定义，索引:', index);
                    // 设置默认图片或占位符
                    img.src = 'data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%22100%25%22%20height%3D%22100%25%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Crect%20width%3D%22100%25%22%20height%3D%22100%25%22%20fill%3D%22%23f0f0f0%22%2F%3E%3Ctext%20x%3D%2250%25%22%20y%3D%2250%25%22%20dominant-baseline%3D%22middle%22%20text-anchor%3D%22middle%22%20fill%3D%22%23ccc%22%3E图片缺失%3C%2Ftext%3E%3C%2Fsvg%3E';
                }
                img.style.width = '100%';
                img.style.height = '100%';
                img.style.objectFit = 'cover';
                previewItem.appendChild(img);
                previewContainer.appendChild(previewItem);
            });
            
            // 添加新增图片按钮
            const addButton = document.createElement('div');
            addButton.className = 'image-item add-image-btn';
            addButton.innerHTML = '+';
            addButton.onclick = function() {
                document.getElementById('photoInput').click();
            };
            previewContainer.appendChild(addButton);
        }



        // 编辑画廊
        function editGallery(galleryId) {
            editGalleryId = galleryId;
            $.ajax({
                url: `/file/gallery/mobile/detail/${galleryId}`,
                type: 'GET',
                success: function(res) {
                    if (res.code === 0) {
                        const gallery = res.data.gallery;
                        const files = res.data.files;
                        currentFiles = files; // 保存当前文件列表
                        
                        // 新增：记录原始文件ID列表
                        originalFileIds = files.map(file => file.id);
                        
                        // 填充表单
                        document.getElementById('galleryTitle').value = gallery.title;
                        document.getElementById('galleryRecordDate').value = formatDate(gallery.recordDate);
                        document.getElementById('galleryShareType').value = gallery.shareType;
                        document.getElementById('galleryDescription').value = gallery.content || '';
                        
                        // 显示预览遮罩层
                        document.getElementById('photoPreviewOverlay').style.display = 'flex';
                        // 隐藏上传按钮
                        document.querySelector('.upload-btn').style.display = 'none';
                        // 显示删除按钮
                        document.getElementById('deleteGalleryBtn').style.display = 'block';
                        
                        // 渲染文件预览
                        const previewContainer = document.getElementById('photoPreviewContainer');
                        previewContainer.innerHTML = '';
                        
                        // 加载画廊中的媒体文件
                        if (gallery.galleryType === 1) {
                            files.forEach((file, index) => {
                                // 创建预览项
                                const previewItem = document.createElement('div');
                                previewItem.className = 'image-item';
                                previewItem.setAttribute('data-index', index);
                                previewItem.setAttribute('draggable', 'true'); // 设置可拖动
                                
                                // 添加拖动事件监听器
                                previewItem.addEventListener('dragstart', handleDragStart.bind(previewItem));
                                previewItem.addEventListener('dragover', handleDragOver.bind(previewItem));
                                previewItem.addEventListener('dragenter', handleDragEnter.bind(previewItem));
                                previewItem.addEventListener('dragleave', handleDragLeave.bind(previewItem));
                                previewItem.addEventListener('drop', handleDrop.bind(previewItem));
                                previewItem.addEventListener('dragend', handleDragEnd.bind(previewItem));
                                
                                // 触摸事件 - 新增
                                previewItem.addEventListener('touchstart', handleTouchStart.bind(previewItem));
                                previewItem.addEventListener('touchmove', handleTouchMove.bind(previewItem));
                                previewItem.addEventListener('touchend', handleTouchEnd.bind(previewItem));

                                // 添加删除按钮
                                const deleteBtn = createDeleteButton(previewContainer, previewItem, index);
                                previewItem.appendChild(deleteBtn);
                                
                                // 创建图片元素
                                const img = document.createElement('img');
                                
                                // 修复：检查file是否存在
                                if (file) {
                                    img.src = file.url || file.thUrl;
                                } else {
                                    console.error('文件对象未定义，索引:', index);
                                    // 设置默认图片或占位符
                                    img.src = 'data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%22100%25%22%20height%3D%22100%25%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Crect%20width%3D%22100%25%22%20height%3D%22100%25%22%20fill%3D%22%23f0f0f0%22%2F%3E%3Ctext%20x%3D%2250%25%22%20y%3D%2250%25%22%20dominant-baseline%3D%22middle%22%20text-anchor%3D%22middle%22%20fill%3D%22%23ccc%22%3E图片缺失%3C%2Ftext%3E%3C%2Fsvg%3E';
                                }
                                img.style.width = '100%';
                                img.style.height = '100%';
                                img.style.objectFit = 'cover';
                                previewItem.appendChild(img);
                                previewContainer.appendChild(previewItem);
                            });
                            // 添加新增图片按钮 - 新增代码
                            const addButton = document.createElement('div');
                            addButton.className = 'image-item add-image-btn';
                            addButton.innerHTML = '+';
                            addButton.onclick = function() {
                                // 触发照片选择
                                document.getElementById('photoInput').click();
                            };
                            previewContainer.appendChild(addButton);
                            // 图片样式
                            previewContainer.style.maxHeight = 'calc(100vh - 250px)';
                            previewContainer.style.overflowY = 'auto';

                            // 图片画廊
                            updateSelectedCount(files.length);
                        } else if (gallery.galleryType === 2) {
                            // 视频画廊
                            document.getElementById('selectedCount').textContent = '已选择: 1 个视频';

                            const previewItem = document.createElement('div');
                            previewItem.className = 'video-preview-item';
                            previewItem.style.width = '100%';
                            previewItem.style.height = '100px';
                            previewItem.style.aspectRatio = '16/9';
                            previewItem.style.position = 'relative';
                            previewItem.style.backgroundColor = '#000';
                            previewItem.style.borderRadius = '8px';

                            const video = document.createElement('video');
                            video.src = files[0].url;
                            video.style.width = '100%';
                            video.style.height = '100%';
                            video.controls = true;
                            video.preload = 'metadata';
                            previewItem.appendChild(video);
                            previewContainer.appendChild(previewItem);
                            
                            // 视频样式
                            previewContainer.style.maxHeight = 'none';
                            previewContainer.style.overflowY = 'visible';
                        }
                    } else {
                        showNotification(res.msg || '获取画廊详情失败');
                    }
                },
                error: function() {
                    showNotification('获取画廊详情失败，请重试');
                }
            });
        }

        // 辅助函数：格式化日期为 YYYY-MM-DD
        function formatDate(dateString) {
            if (!dateString) return '';
            const date = new Date(dateString);
            return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
        }

        // 上一张/上一个
        function prevItem() {
            if (currentFiles.length <= 1) return;

            currentIndex = (currentIndex - 1 + currentFiles.length) % currentFiles.length;

            if (currentGallery.galleryType === 1) {
                $('#viewer-image').attr('src', currentFiles[currentIndex].url);
            } else if (currentGallery.galleryType === 2) {
                const video = $('#viewer-video')[0];
                video.pause();
                video.src = currentFiles[currentIndex].url;
                video.play();
            }
        }

        // 删除画廊记录
        function deleteGallery() {
            if (!editGalleryId) {
                showNotification('没有选择要删除的画廊');
                return;
            }

            // 显示确认对话框
            if (confirm('确定要删除这个画廊吗？此操作不可撤销。')) {
                // 显示加载中
                showLoading('删除中...');

                $.ajax({
                    url: `/file/gallery/mobile/delete/${editGalleryId}`,
                    type: 'POST',
                    success: function(res) {
                        hideLoading();
                        if (res.code === 0) {
                            showNotification('删除成功');
                            closePreview();
                            // 刷新画廊列表
                            location.reload();
                        } else {
                            showNotification(res.msg || '删除失败');
                        }
                    },
                    error: function() {
                        hideLoading();
                        showNotification('删除失败，请重试');
                    }
                });
            }
        }

        // 下一张/下一个
        function nextItem() {
            if (currentFiles.length <= 1) return;

            currentIndex = (currentIndex + 1) % currentFiles.length;

            if (currentGallery.galleryType === 1) {
                $('#viewer-image').attr('src', currentFiles[currentIndex].url);
            } else if (currentGallery.galleryType === 2) {
                const video = $('#viewer-video')[0];
                video.pause();
                video.src = currentFiles[currentIndex].url;
                video.play();
            }
        }

        document.addEventListener('touchstart', function(e) {
            if (!isViewerOpen) return;
            touchStartX = e.touches[0].screenX;
        }, false);

        document.addEventListener('touchend', function(e) {
            if (!isViewerOpen) return;
            touchEndX = e.changedTouches[0].screenX;
            handleSwipe();
        }, false);

        function handleSwipe() {
            if (touchEndX < touchStartX - 50) {
                // 向左滑动，下一张
                nextItem();
            } else if (touchEndX > touchStartX + 50) {
                // 向右滑动，上一张
                prevItem();
            }
        }
    </script>
</body>
</html>
